// utils/document.ts
import { Doc } from "@/api/interface/doc";

/**
 * 根据ID在文档树中查找节点
 * @param nodes 文档树节点数组
 * @param id 要查找的节点ID
 * @returns 找到的节点或null
 */
export const findNodeById = (nodes: Doc.DocNode[], id: string): Doc.DocNode | null => {
  for (const node of nodes) {
    if (node.FId === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
};

/**
 * 查找树中的第一个文档节点(非文件夹)
 * @param nodes 文档树节点数组
 * @returns 第一个文档节点或null
 */
export const findFirstDoc = (nodes: Doc.DocNode[]): Doc.DocNode | null => {
  for (const node of nodes) {
    if (node.FType === "doc") return node;
    if (node.children?.length) {
      const doc = findFirstDoc(node.children);
      if (doc) return doc;
    }
  }
  return null;
};

/**
 * 从文档树中删除指定ID的节点
 * @param nodes 文档树节点数组
 * @param id 要删除的节点ID
 * @returns 是否删除成功
 */
export const deleteNodeFromTree = (nodes: Doc.DocNode[], id: string): boolean => {
  for (let i = 0; i < nodes.length; i++) {
    if (nodes[i].FId === id) {
      nodes.splice(i, 1);
      return true;
    }
    if (nodes[i].children?.length && deleteNodeFromTree(nodes[i].children!, id)) {
      return true;
    }
  }
  return false;
};

/**
 * 扁平化文档树结构
 * @param nodes 文档树节点数组
 * @returns 扁平化的文档节点数组
 */
export const flattenDocTree = (nodes: Doc.DocNode[]): Doc.DocNode[] => {
  return nodes.reduce<Doc.DocNode[]>((acc, node) => {
    acc.push(node);
    if (node.children) {
      acc.push(...flattenDocTree(node.children));
    }
    return acc;
  }, []);
};

/**
 * 过滤文档树，返回匹配搜索条件的节点
 * @param nodes 文档树节点数组
 * @param keyword 搜索关键词
 * @returns 过滤后的文档树
 */
export const filterDocTree = (nodes: Doc.DocNode[], keyword: string): Doc.DocNode[] => {
  if (!keyword) return nodes;

  return nodes.reduce<Doc.DocNode[]>((acc, node) => {
    const matches = node.FTitle.toLowerCase().includes(keyword.toLowerCase());
    const children = node.children ? filterDocTree(node.children, keyword) : [];

    if (matches || children.length > 0) {
      acc.push({
        ...node,
        children: children.length > 0 ? children : undefined
      });
    }

    return acc;
  }, []);
};
